package domain.worm;

import images.Images;

import com.uqbar.vainilla.DeltaState;
import com.uqbar.vainilla.appearances.Appearance;

public class WalkingState extends WormState {

	public WalkingState(Worm worm) {
		super(worm);
		worm.setAppearance(getWalkingAnimation(worm.getDir()));

	}
	
	private Appearance getWalkingRightAnimation() {
		return Images.getAnimation("walkRight", 0.4);
	}
	private Appearance getWalkingLeftAnimation() {
		return Images.getAnimation("walkLeft", 0.4);
	}

	public void walk(DeltaState deltaState, int dir) {
		this.getWorm().setDir(dir);
		if(this.getWorm().canWalk(deltaState, dir)){
			this.normalWalk(deltaState, dir);
		}
		else {
			if (this.canClimb(deltaState, dir)){
				this.climb(deltaState, dir);
			}else{
				this.getWorm().setAppearance(getWalkingAnimation(dir));}
			
		}
	}

	private Appearance getWalkingAnimation(int dir) {
		if (dir == 1){
			return this.getWalkingRightAnimation();
		}else {
			return this.getWalkingLeftAnimation();
		}
		
	}

	private boolean canClimb(DeltaState delta, int dir) {
		double nX, nY;
		nX = this.getWorm().getX() + this.getWorm().getSpeed()*dir*delta.getDelta() +dir;
		nY = this.getWorm().getY() + this.getWorm().getMoveCap();
		return !this.getWorm().getScene().getTerrain().isCollision(nX, nY, this.getWorm().getDiameter(), this.getWorm().getHeight());
		
	}

	private void climb(DeltaState deltaState, int dir) {
		this.getWorm().updateCoords(0, this.getWorm().getMoveCap());
		this.getWorm().nonSolidMove(deltaState, this.getWorm().getSpeed(), dir*2, 0, 0, 0);
		this.getWorm().setState(new StateFalling(this.getWorm()));
	}

	private void normalWalk(DeltaState delta, int dir) {
		double diffX, diffY;
		this.getWorm().setAppearance(this.getWalkingAnimation(dir));
		diffX = delta.getDelta()*this.getWorm().getSpeed()*dir;
		
		this.getWorm().updateCoords(diffX, 0);
		this.getWorm().setState(new StateFalling(this.getWorm()));
		
	}
	

	@Override
	public void update(DeltaState deltaState) {
	}

}
